!(function (e) {
  // body...
  var ELEM = '.xh-form',
    MOD_NAME = 'form';
  Form = function (s) {
    this.config = {
      verify: {
        required: [/[\S]+/, '必填项不能为空'],
        name: [/[\S]+/, '姓名不能为空'],
        phone: [/^1\d{10}$/, '请输入正确的手机号'],
        email: [
          /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,
          '邮箱格式不正确',
        ],
        url: [/(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/, '链接格式不正确'],
        number: function (value) {
          if (!value || isNaN(value)) return '只能填写数字';
        },
        date: [
          /^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/,
          '日期格式不正确',
        ],
        identity: [/(^\d{15}$)|(^\d{17}(x|X|\d)$)/, '请输入正确的身份证号'],
      },
    };
  };
  //验证规则设定
  Form.prototype.verify = function (settings) {
    var that = this;
    $.extend(true, that.config.verify, settings);
    return that;
  };
  //取值
  Form.prototype.getValue = function (filter, itemForm) {
    itemForm = itemForm || $(ELEM + '[xh-filter="' + filter + '"]').eq(0);
    var nameIndex = {}, //数组 name 索引
      field = {},
      fieldElem = itemForm.find('input,select,textarea'); //获取所有表单域
    $.each(fieldElem, function (_, item) {
      item.name = (item.name || '').replace(/^\s*|\s*&/, '');
      if (!item.name) return;
      //用于支持数组 name
      if (/^.*\[\]$/.test(item.name)) {
        var key = item.name.match(/^(.*)\[\]$/g)[0];
        nameIndex[key] = nameIndex[key] | 0;
        item.name = item.name.replace(
          /^(.*)\[\]$/,
          '$1[' + nameIndex[key]++ + ']'
        );
      }
      if (/^checkbox|radio$/.test(item.type) && !item.checked) return;
      field[item.name] = item.value;
    });

    return field;
  };
  var ajax = function (field, formElem, host) {
    $.ajax({
      url: host + '/plus/diy.php',
      type: 'POST',
      dataType: 'json',
      data: field,
      success: function (e) {
        if (e.state == 1) {
          layer.open({
            content: '提交成功，稍后会有专人与您联系，请您稍作等待...',
            btn: '我知道了',
          });
          formElem.reset();
        } else {
          layer.open({
            content: '提交失败，或者您可以直接拨打电话沟通！',
            btn: '我知道了',
          });
          return false;
        }
      },
    }).fail(function (err) {
      layer.open({
        content: '提交失败，或者您可以直接拨打电话沟通！',
        btn: '我知道了',
      });
      console.log(err);
    });
    return false;
  };
  //表单提交校验
  var submit = function () {
    var stop = null, //验证不通过状态
      verify = form.config.verify, //验证规则
      DANGER = 'xh-form-danger', //警示样式
      field = {}, //字段集合
      button = $(this), //当前触发的按钮
      elem = button.parents(ELEM), //当前所在表单域
      verifyElem = elem.find('*[xh-verify]'), //获取需要校验的元素
      formElem = button.parents('form')[0], //获取当前所在的 form 元素，如果存在的话
      filter = button.attr('xh-filter'); //获取过滤器
    host = elem.attr('host');
    //开始校验
    $.each(verifyElem, function (_, item) {
      var othis = $(this),
        vers = othis.attr('xh-verify').split('|'),
        verType = othis.attr('xh-verType'), //提示方式
        value = othis.val();
      othis.removeClass(DANGER); //移除警示样式
      //遍历元素绑定的验证规则
      $.each(vers, function (_, thisVer) {
        var isTrue, //是否命中校验
          errorText = '', //错误提示文本
          isFn = typeof verify[thisVer] === 'function';
        //匹配验证规则
        if (verify[thisVer]) {
          var isTrue = isFn
            ? (errorText = verify[thisVer](value, item))
            : !verify[thisVer][0].test(value);
          errorText = errorText || verify[thisVer][1];
          if (thisVer === 'required') {
            errorText = othis.attr('xh-reqText') || errorText;
          }
          //如果是必填项或者非空命中校验，则阻止提交，弹出提示
          if (isTrue) {
            layer.open({
              content: errorText,
              btn: '我知道了',
            });
            setTimeout(function () {
              item.focus();
            }, 7);
            othis.addClass(DANGER);
            return (stop = true);
          }
        }
      });
      if (stop) return false;
      //if (stop) return stop;
    });
    if (stop) return false;
    //获取当前表单值
    field = form.getValue(null, elem);
    //返回字段
    ajax(field, formElem, host);
    return false;
  };
  var form = new Form(),
    $dom = $(document),
    $win = $(window);
  $dom.on('submit', ELEM, submit).on('click', '*[xhcss]', submit);
})(window);
